<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--节点数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
              v-model="name"
              placeholder="请输入节点名称"
              clearable
              prefix-icon="Search"
              style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
              :data="tableOptions"
              :props="{ label: 'label', children: 'children' }"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="TreeRef"
              node-key="id"
              highlight-current
              default-expand-all
              @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">

          <el-form-item label="年份" prop="nf">
            <el-input
                v-model="queryParams.nf"
                placeholder="请输入年份"
                clearable
                style="width: 240px"
                @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
                type="primary"
                plain
                icon="Plus"
                @click="handleAdd"
                v-hasPermi="['system:table:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="success"
                plain
                icon="Edit"
                :disabled="single"
                @click="handleUpdate"
                v-hasPermi="['system:table:edit']"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="danger"
                plain
                icon="Delete"
                :disabled="multiple"
                @click="handleDelete"
                v-hasPermi="['system:table:remove']"
            >删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="info"
                plain
                icon="Upload"
                @click="handleImport"
                v-hasPermi="['system:table:import']"
            >导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="warning"
                plain
                icon="Download"
                @click="handleExport"
                v-hasPermi="['system:table:export']"
            >导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>
<!--        数据展示表格-->
        <el-table
            v-loading="loading"
            :data="tableData"
            :selection="selectionRows"
            border
            :row-style="{ height: '40px' }"
            tooltip-effect="light"
            @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column type="index" label="序号"  width="75" />
          <!-- 渲染动态列 -->
          <el-table-column
              v-for="column in dynamicColumns"
              :key="column.key"
              :label="column.label"
              :prop="column.prop"
              :show-overflow-tooltip="true"
              style="white-space: nowrap"
              min-width="100%"
          >
            <template #header>
              <!-- 小提示框 -->
              <el-tooltip
                  :disabled="isShowTooltip"
                  :content="column.label"
                  placement="top"
              >
                <!-- 单行省略样式、鼠标移入事件 -->
                <div class="singe-line" @mouseover="onMouseOver($event.target)">
                  {{ column.label }}
                </div>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
<!--        分页器-->
        <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
        />
      </el-col>
    </el-row>
<!--    新增或修改弹框-->
    <el-dialog v-model="open" :title="title" @close="closeAddModal" width="600px" append-to-body>
      <el-form ref="addFormRef" :model="formData" :rules="formRules" label-width="80px">
        <el-row :gutter="20"> <!-- 设置栅格间隔 -->
          <el-col :span="12" v-for="column in dynamicColumns" :key="column.prop">
            <el-form-item :label="column.label" :prop="column.prop">
              <el-input v-if="isInputType(column)" v-model="formData[column.prop]"></el-input>
              <!-- 根据不同类型的列添加不同的表单控件 -->
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <!-- 提交按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">保存</el-button>
          <el-button @click="closeAddModal">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 数据导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload
          ref="uploadRef"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?updateSupport=' + upload.updateSupport"
          :disabled="upload.isUploading"
          :file-list="uploadFiles"
          :on-change="loadJsonFromFile"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="details">
import { getToken } from "@/utils/auth";
import {  delUser, getUser, updateUser, addUser } from "@/api/system/user";
import {getCurrentInstance, reactive, ref, toRefs, watch, onMounted,onActivated} from "vue";
import {useRouter} from "vue-router";
import {getTableData, addData, tableTreeSelect, updateData, delData, importDataList} from "@/api/shenji/table";
import {useDetailsStore} from "@/store/modules/details";
import * as XLSX from "xlsx";
const store = useDetailsStore();
const router = useRouter();
const { proxy } = getCurrentInstance();
const { sys_normal_disable, sys_user_sex } = proxy.useDict("sys_normal_disable", "sys_user_sex");
let uploadFiles = [];
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const name = ref("");
const deptName = ref("");
const tableOptions = ref(undefined);
const tableData = ref([]);
const dynamicColumns = ref([]);
const isShowTooltip = ref(true);
const tooltipTarget = ref(null); // 引用可能文本溢出的元素
const formData = ref({});
const formRules = ref({});
const addFormRef = ref(null); // 对表单进行引用
const selectionRows = ref([]);
const onMouseOver = (target) => {
  // 判断是否开启tooltip功能
  if (target.scrollWidth > target.clientWidth) {
    isShowTooltip.value = false;
  } else {
    isShowTooltip.value = true;
  }
};
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/system/user/importData"
});
const change = reactive({
  // 是否显示弹出层（增加修改）
  open: false,
  // 弹出层标题（增加修改）
  title: "",
})
// 列显隐信息
const columns = ref([
  { key: 0, label: `用户编号`, visible: true },
  { key: 1, label: `用户名称`, visible: true },
  { key: 2, label: `用户昵称`, visible: true },
  { key: 3, label: `部门`, visible: true },
  { key: 4, label: `手机号码`, visible: true },
  { key: 5, label: `状态`, visible: true },
  { key: 6, label: `创建时间`, visible: true }
]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: undefined,
    name: undefined
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);



const closeAddModal = () => {
  open.value = false;
  formData.value = {};
};

const handleSubmit = () => {

  const sendData = formData.value;
  sendData.tableId = queryParams.value.id;

  proxy.$refs["addFormRef"].validate(valid => {
    if (valid) {
      if (formData.value.id != undefined) {
        updateData(sendData).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addData(sendData).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
      closeAddModal();
    }
  });

};

const isInputType = (column) => {
  // 根据column定义判断是否为文本输入类型，这里只是一个简单的示例
  return true; // 或者更具实际情况进行判断
};


/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};
/** 根据名称筛选部门树 */
watch(name, val => {
  proxy.$refs["TreeRef"].filter(val);
});

/** 查询部门下拉树结构 */
function getTableTree() {
  tableTreeSelect().then(response => {
    console.log("response",response);
    tableOptions.value = response.data;
  });
};

/** 查询用户列表 */
function getList() {
  loading.value = true;
  tableData.value = [];
  dynamicColumns.value = [];
  if(queryParams.value.id == undefined){
    return;
  }
  console.log("proxy.addDateRange(queryParams.value, dateRange.value)",proxy.addDateRange(queryParams.value, dateRange.value));
  console.log("queryParams.value,dateRange.value",queryParams.value,dateRange.value);
  getTableData(proxy.addDateRange(queryParams.value, dateRange.value)).then(res => {
    console.log("getTableData.recived",res.rows);
    tableData.value = res.rows;
    total.value = res.total;
    tableData.value = tableData.value.slice(1);
    let relationMap = res.rows[0];
    if(relationMap['nf'] !== undefined){
      dynamicColumns.value.push({
        key: 'nf',
        label: relationMap['nf'],
        prop: 'nf'
      })
    }

    Object.keys(relationMap).forEach(myKey => {
      if(myKey !== 'nf'){
        dynamicColumns.value.push({
          key: myKey,
          label: relationMap[myKey],
          prop: myKey
        })
      }

    });
    loading.value = false;

  });
};

/** 节点单击事件 */
function handleNodeClick(data) {
  queryParams.value.id = data.id;
  queryParams.value.name = data.label;
  console.log("data",data);

  handleQuery();
};

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  loading.value = true;
  getList();
};

/** 重置按钮操作 */
function resetQuery() {
  loading.value = true;
  dateRange.value = [];
  proxy.resetForm("queryRef");
  proxy.$refs.tree.setCurrentKey(null);
  handleQuery();
};
/** 删除按钮操作 */
function handleDelete(row) {
  ids.value = selectionRows.value.map(item => item.id);

  proxy.$modal.confirm('是否确认删除数据编号为"' + ids.value + '"的数据项？').then(function () {
    ids.value.unshift(queryParams.value.id);
    return delData(ids.value);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
};
/** 导出按钮操作 */
function handleExport() {
  proxy.download("system/user/export", {
    ...queryParams.value,
  },`user_${new Date().getTime()}.xlsx`);
};


/** 选择条数  */
function handleSelectionChange(selection) {
  selectionRows.value = selection.map(item => item);
  console.log("selectionRows",selectionRows);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};
/** 导入按钮操作 */
function handleImport() {
  upload.title = "用户导入";
  upload.open = true;
};

/** 下载模板操作 */
function importTemplate() {
  proxy.download("shenji/table/importTemplate"+"/"+queryParams.value.id,{},queryParams.value.name+`_template_${new Date().getTime()}.xlsx`);
};
/** 文件发生变化 */
const loadJsonFromFile = (file, fileList) =>{

  uploadFiles = fileList;
  console.log("uploadFiles;{}",uploadFiles)
}
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  console.log("fileList;{}",fileList)
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  console.log("fileLis",fileList)
  upload.open = false;
  upload.isUploading = false;
  let myFile = uploadFiles[0];
  const reader = new FileReader();
  reader.readAsArrayBuffer(myFile.raw); // 使用 readAsArrayBuffer 读取 Excel 文件
  reader.onload = (e) => {
// 读取文件内容
    const bufferArray = e.target.result;

    // 将文件内容解析为 Workbook 对象
    const workbook = XLSX.read(bufferArray, { type: 'array' });
    // const data = new Uint8Array(e.target.result);
    // const workbook = XLSX.read(data, { type: "array" });
    //
    const firstSheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[firstSheetName];

    let excelData = XLSX.utils.sheet_to_json(worksheet, { raw: true });
    console.log("workbook",workbook);
    excelData[0].tableId = queryParams.value.id;
    console.log("excelData",excelData);
    importDataList(excelData)
        .then((response) => {
          // 处理上传成功后的响应
          console.log(response);
          proxy.$modal.msgSuccess("导入成功");
          getList();
        })
        .catch((error) => {
          // 处理上传失败后的错误
          console.error(error);
          proxy.$modal.msgSuccess("导入失败");
        });
  };
  proxy.$refs["uploadRef"].handleRemove(file);

  // getList();
};
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};
/** 重置操作表单 */
function reset() {
  form.value = {
    userId: undefined,
    deptId: undefined,
    userName: undefined,
    nickName: undefined,
    password: undefined,
    phonenumber: undefined,
    email: undefined,
    sex: undefined,
    status: "0",
    remark: undefined,
    postIds: [],
    roleIds: []
  };
  proxy.resetForm("userRef");
};
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
};
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加数据";

};
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  formData.value = selectionRows.value[0];
  console.log("formData.value:",formData.value);
  open.value = true;
  title.value = "修改用户";

};
getTableTree();
// 监听store.row.id的变化
watch(
    () => store.row, // 这里返回一个getter函数获取需要监视的值
    (newValue, oldId) => {
      if (newValue !== undefined) {
        queryParams.value.id = newValue.id;
        queryParams.value.name = newValue.name;
        getList();
      }
    },
    { immediate: true } // 如果希望在初次渲染时就执行回调，可以设置immediate为true
);
onMounted(() => {
  if (store.row && store.row.id) {
    queryParams.value.id = store.row.id;
    queryParams.value.name = store.row.name;
  }
});
/** 主动暴露方法 */
onActivated(()=>{
  // queryParams.value.id = store.row.id;
  // console.log("queryParams.value.id:",queryParams.value.id);
  // getList();

})
</script>

<style>
.singe-line {
  text-overflow: ellipsis;
  overflow: hidden;
  word-break: break-all;
  white-space: nowrap;
}
</style>